package com.atguigu.lease.web.admin.schedule;


import com.atguigu.lease.model.entity.GraphInfo;
import com.atguigu.lease.model.entity.LeaseAgreement;
import com.atguigu.lease.model.entity.RoomInfo;
import com.atguigu.lease.model.enums.LeaseStatus;
import com.atguigu.lease.model.service.GraphInfoService;
import com.atguigu.lease.model.service.LeaseAgreementService;
import com.atguigu.lease.model.service.RoomInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.minio.MinioClient;
import io.minio.RemoveObjectArgs;
import io.minio.RemoveObjectsArgs;
import io.minio.errors.*;
import io.minio.messages.DeleteObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Component
public class ScheduledTasks {

    @Autowired
    LeaseAgreementService leaseAgreementService;

    @Autowired
    RoomInfoService roomInfoService;

    @Autowired
    GraphInfoService graphInfoService;

    @Autowired
    MinioClient minioClient;



    @Scheduled(cron = "0 0 0 * * *")
    public void checkLeaseAgreement(){

        LambdaUpdateWrapper<LeaseAgreement> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        Date nowDate = new Date();
        lambdaUpdateWrapper.le(LeaseAgreement::getLeaseEndDate,nowDate);
        lambdaUpdateWrapper.in(LeaseAgreement::getStatus, LeaseStatus.SIGNED,LeaseStatus.WITHDRAWING);//对应2和5  代表是否在租
        lambdaUpdateWrapper.set(LeaseAgreement::getStatus,LeaseStatus.EXPIRED); //对应已到期


        leaseAgreementService.update(lambdaUpdateWrapper);


    }

    @Scheduled(cron="0 0 0 * * *")
    public void checkRoomGraph() throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        LambdaQueryWrapper<GraphInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GraphInfo::getIsDeleted,1);
        List<GraphInfo> list = graphInfoService.listRemove();

        for (GraphInfo graphInfo : list) {
            if (graphInfo.getUrl()==null){
                continue;
            }
            String[] split = graphInfo.getUrl().split("/");
            String graname = split[split.length-1];
            System.out.println(graname);
            RemoveObjectArgs lease = RemoveObjectArgs.builder().bucket("lease").object(graname).build();
            minioClient.removeObject(lease);
        }


    }



}
